<?php

namespace app\batch;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use app\models\{Order, Quotes, Price};
use think\Db;
use app\facade\Redis;
use think\facade\Debug;


class CreatOrder extends Command
{
    private $url = 'https://api-aws.huobi.pro/';

    protected function configure()
    {
        $this->setName('CreatOrder')->setDescription('生成假订单');
    }

    protected function execute(Input $input, Output $output)
    {
        $this->doCron();
        die();
    }

    protected function doCron()
    {
        $cmd = "ps aux | grep '/www/server/php/72/bin/php /www/wwwroot/JTE/think MatchOrder'|grep -v 'grep'| awk '{print $2}'";
        exec($cmd, $ps, $ret);
        if (count($ps) > 1) {
            die("batch of  is running");
        }
        ini_set('max_execution_time', 0);
        $price = (new Price())->order('date desc')->where('date', '<=', date('Y-m-d'))->value('price') ?? 0;
        (new Quotes())->where(['ishow' => 1, 'type' => 2])->chunk(1, function ($list) use ($price) {
            foreach ($list as $lists) {
                $url = $this->url . "market/history/kline?symbol=" . strtolower($lists['coin2'] . $lists['mart']) . '&period=1day&size=1';
                $result = api_curl($url);
                $client = json_decode($result, true);
                if (!empty($client['status']) && $client['status'] == 'ok') {
                    $quto = floor(($client['data'][0]['close'] - $client['data'][0]['open']) * 1000000 / $client['data'][0]['open']) / 10000;
                    $quto = $quto * (1 + 0.07);
                    $data = [
                        'type' => rand(1, 2),
                        'coin' => $lists['coin'],
                        'mart' => $lists['mart'],
                        'commnum' => rand(100, 10000) / 100,
                        'commprice' => floor($price * (100 + $quto) * 100) / 10000,
                    ];
                    dump($quto);
                    dump($data);
                    if ($data['commprice'] < 0) {
                        $data['commprice'] = floor($price * (100 + abs($quto)) * 100) / 10000;
                    }
                    $data['transnum'] = $data['commnum'];
                    $data['transprice'] = $data['commprice'];
                    $data['commtotal'] = $data['commnum'] * $data['commprice'];
                    $data['transtotal'] = $data['transnum'] * $data['transprice'];
                    $data['status'] = 2;
                }
                Db::startTrans();
                try {
                    (new Order())->save($data);
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    dump($e->getMessage());
                }
            }
        });
    }
}
